<template>
  <!-- 上方分类选项 -->
  <Category :scene="scene" />
  <!-- 下方内容展示 -->
  <el-card style="margin: 10px 0px">
    <div v-show="scene === 0">
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        :disabled="categoryStore.c3Id == '' ? true : false"
        @click="handleAdd"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0px" :data="attrArr">
        <!-- eslint-disable -->
        <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
        <!--                                                   值 -->
        <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin: 0px 5px">
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="Edit" @click="handleEdit(row)"></el-button>
            <!--                            传的不是$index而是row.id,因为$index表示的是attrArr中row的下标,而delete接口需要数据的id -->
            <!-- 确定气泡 -->
            <el-popconfirm :title="`你确定要删除${row.attrName}?`" @confirm="handleDelete(row.id)">
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <!-- eslint-enable -->
      </el-table>
    </div>
    <div v-show="scene === 1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
        </el-form-item>
      </el-form>
      <!--                                                     为属性添加一个标签          有属性名才可以进一步添加标签 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addAttrValue"
        :disabled="attrParams.attrName ? false : true"
      >
        添加属性值
      </el-button>
      <el-button type="primary" size="default" @click="handleCancel">取消</el-button>
      <el-table border style="margin: 10px 0px" :data="attrParams.attrValueList">
        <!-- eslint-disable -->
        <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              v-if="row.flag"
              @blur="handleSwitch(row, $index)"
              v-model="row.valueName"
            ></el-input>
            <div v-else @click="handleSwitch(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="() => attrParams.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--                                                                       有至少一个标签才能保存-->
      <el-button
        type="primary"
        size="default"
        @click="handleSaveAttr"
        :disabled="!attrParams.attrValueList.length"
      >
        保存
      </el-button>
      <el-button type="primary" size="default" @click="handleCancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
//引入categoryStore小仓库
import useCategoryStore from '@/store/modules/category'
//通过c3Id获取已有属性数据的接口方法
import { reqAttr, reqAddorUpdateAttr, reqDeleteAttr } from '@/api/product/attr/index'
//引入属性与属性值ts类型
import { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
//获取分类的仓库
let categoryStore = useCategoryStore()
//存储已有属性和属性值
let attrArr = ref<Attr[]>([])
//添加表单显示与否
let scene = ref<number>(0)
//收集新增属性标签的数组
let attrParams = reactive<Attr>({
  attrName: '', //新增属性名
  attrValueList: [], //新增属性数组
  categoryId: '', //三级分类id
  categoryLevel: 3, //三级分类
})
//修改/添加标签时的每个input组件，每次点击时自动聚焦
let inputArr = ref<any>([])
//监测c3Id，获取已有属性数据
watch(
  () => categoryStore.c3Id,
  () => {
    //每次发请求都先清空之前的数据
    attrArr.value = []
    if (!categoryStore.c3Id) return
    getAttr()
  },
)
//获取已有属性数据的方法
const getAttr = async () => {
  //解构形式
  const { c1Id, c2Id, c3Id } = categoryStore
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  console.log(result.data)
  if (result.code === 200) {
    attrArr.value = result.data
  }
}
//改变scene，显示添加属性
const handleAdd = () => {
  //每次点击前，先清空之前的attrParams数据
  Object.assign(attrParams, {
    attrName: '', //新增属性名
    attrValueList: [], //新增属性数组
    categoryId: categoryStore.c3Id, //三级分类id
    categoryLevel: 3, //三级分类
  })
  scene.value = 1
}
//取消增加属性
const handleCancel = () => {
  scene.value = 0
}
//增加属性标签
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    //控制每个属性值编辑模式与切换模式的切换
    flag: true,
  })
}
//保存新属性
const handleSaveAttr = async () => {
  let result: any = await reqAddorUpdateAttr(attrParams)
  if (result.code === 200) {
    scene.value = 0
    getAttr()
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改属性成功' : '添加属性成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改属性失败' : '添加属性失败',
    })
  }
}
//添加/修改属性时标签的编辑/观察模式切换
const handleSwitch = (row: AttrValue, $index: number) => {
  //如果输入的标签值为空
  if (row.valueName.trim() == '') {
    //删除标签值为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '标签值不能为空',
    })
    return
  }
  //如果输入的标签值重复
  if (
    attrParams.attrValueList.find((item) => {
      //把row剔除
      if (item !== row) return item.valueName === row.valueName
    })
  ) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '标签值不能重复',
    })
    return
  }
  row.flag = !row.flag
  nextTick(() => {
    // 修改时自动聚焦
    if (inputArr.value[$index]) {
      inputArr.value[$index].focus()
    }
  })
}
//修改已有属性值
const handleEdit = (row: Attr) => {
  scene.value = 0
  //要用JSON变成深拷贝，否则修改的时候取消修改，row仍然会改变，因为浅拷贝的情况row和attrParams用的同一个指针
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
//删除已有属性值
const handleDelete = async (id: number) => {
  let result = await reqDeleteAttr(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: result.data,
    })
  }
}
//转入其他界面时，销毁仓库里category的数据
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped lang="scss"></style>
